package com.itheima.controller;

import com.itheima.pojo.PageResult;
import com.itheima.pojo.User;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {


    @Autowired
    private IUserService userService;

    //分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable int currentPage, @PathVariable int pageSize) throws IOException {
        List<User> userList = userService.selectByPage(currentPage, pageSize);
        Integer totalCount = userService.selectTotalCount();
        return new Result(Code.GET_OK, new PageResult(totalCount, userList));
    }

    /**
     * 保存用户
     *
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        int result = userService.add(user);
        return new Result(Code.SAVE_OK, result == 1 ? "新增成功" : "新增失败");
    }


    /**
     * 根据用户id删除
     *
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int result = userService.deleteById(id);
        return new Result(Code.DELETE_OK, result == 1 ? "新增成功" : "新增失败");
    }

    /**
     * 更新用户
     *
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        int result = userService.update(user);
        return new Result(Code.UPDATE_OK, result == 1 ? "新增成功" : "新增失败");
    }



}
